package edu.rpi.bt.server.dao;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import com.aetrion.flickr.Flickr;
import com.aetrion.flickr.FlickrException;
import com.aetrion.flickr.REST;
import com.aetrion.flickr.photos.Photo;
import com.aetrion.flickr.photos.PhotoList;
import com.aetrion.flickr.photos.PhotosInterface;
import com.aetrion.flickr.photos.SearchParameters;


public class FlickrSearch {
    String[] URLs;
    public String[] getURLs(){
        return URLs;
    }
    public FlickrSearch(String searchString,int num){
        String[] urls=new String[num];
        //Set api key
        String key="fa5fe3b64297e9b5a8f878287605d38f";
        String svr="www.flickr.com";
        String secret="4b2ac9446928ffe3";
        REST rest = null;
        try {
            rest = new REST();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        rest.setHost(svr);
       
        //initialize Flickr object with key and rest
        Flickr flickr=new Flickr(key,rest);
        Flickr.debugStream=false;
        flickr.setSharedSecret(secret);
        //initialize SearchParameter object, this object stores the search keyword
        SearchParameters searchParams=new SearchParameters();
        searchParams.setSort(SearchParameters.RELEVANCE);
       
        //Create tag keyword array
        searchParams.setText(searchString);
    
        //Initialize PhotosInterface object
        PhotosInterface photosInterface=flickr.getPhotosInterface();
        //Execute search with entered tags
        PhotoList photoList = null;
        try {
            photoList = photosInterface.search(searchParams,num,1);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FlickrException e) {
            // TODO Auto-generated catch block
            System.out.println(e.getErrorMessage());
        }
    
        //get search result and fetch the photo object and get url
        if(photoList!=null){
           //Get search result and check the size of photo result
           for(int i=0;i<photoList.size();i++){
              //get photo object
              Photo photo=(Photo)photoList.get(i);
              urls[i]=photo.getMediumUrl();
           }
        }
        URLs = urls;
    }
}